$(function(){
    $('nav#menu_left').mmenu();
    $("nav#menu_right").mmenu({
        offCanvas: {
            position  : "right"
        }
    }).on('closed.mm', function(){
            AlertBox.closeAlertBox();
        });
    $('#actlist').on('click', '.faction_act', function(e){
        var id = $(this).attr('data-id');
        window.location.href = '/invite/'+id;
    })
    $('#factionActBtn').on('click', function(){
        window.location.href = '/create/'+factionId;
    });
    $('#factionInfoBtn').live('click', function(){
        //window.location.href = '/faction/info/'+factionId;
        $('.toShare').trigger('click')
    })
    $('#title').on('click', function(e){
        window.location.href = '/faction/info/'+factionId;
    })
    /*$('#members').on('click', 'li', function(e){
        var id = $(this).attr('data-id');
        window.location.href = '/user/'+id+'/'+factionId;
    })*/
    $('#myTab a').click(function (e) {
        e.preventDefault()
        $(this).tab('show')
    });
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        if($(e.target).attr('href') === '#members'){
            _fetchMembers(function(members, pageNo){
                if(members.length >0) $('#pageNo').val(pageNo);
                _renderList(members)
            })
        }
        if($(e.target).attr('href') === '#goods'){
            _fetchGoods()
        }
        //e.target // activated tab
        //e.relatedTarget // previous tab
    });
    $('.goods-item').live('click', function(e){
        window.location.href = '/showGoods/'+$(this).data('id')
    })
    $('#loadMore').live('click', function(e){
        _fetchMembers(function(members, pageNo){
            if(members.length >0) $('#pageNo').val(pageNo);
            _renderList(members)
        })
    });
    $('#loadMoreAct').on('click', function(){
        _fetchActs();
    })
    $('.tick_out').live('click', function(e){
        var _self = $(this);
        var id = _self.attr('data-id'),
            name = _self.attr('data-name'),
            content = '确定要将Ta移出圈子？<br/><img src="/img/'+id+'" class="img-rounded size_24"/><a>'+name+'</a>';
        AlertBox.showConfirm(content, {ok:'是的', cancel:'取消'}, function(){
            AlertBox.closeAlertBox();
            _tickUserOut(id, function(){
                 _self.parent().parent().fadeOut('slow', function(){
                    $(this).remove();
                 });
            });
        }, function(){
            AlertBox.closeAlertBox();
        });
    });
})
function _tickUserOut(id, callback){
    $.post('/faction/tick', {id: id, faction: factionId}, function(res){
        if(res.error){ return AlertBox.showTip('出了问题了...')}
        callback()
    })
}
function _fetchMembers(cb){
    $.getJSON('/faction/members/'+factionId+'/'+($('#pageNo').val() || 1), function(res){
        cb(res.members, res.pageNo);
    })
}
function _fetchGoods(){
    $.ajax({
        url: '/fetchGoods/'+factionId,
        type: 'GET',
        dataType: 'text',
        success: function(res){
            $('#goods').html(res)
        }
    })
}
function _renderList(members){
    var html = '';
    if(members.length > 0){
        if($('#memberlist').length == 0){
            var listContainer = '<div class="bg_white_panel" style="margin-top: 15px;"><ul id="memberlist"></ul>';
            if(members.length == 10)
                listContainer += '<div id="loadMore">查看更多<span class="icon-arrow-down"></span></div>';
            listContainer += '</div><input type="hidden" id="pageNo" value="2"/>';
            listContainer +='<div style="margin-top:10px;">\
                                <button type="button" class="btn btn-success btn-block toShare"><strong>拉小伙伴们进圈子</strong></button>\
                            </div>';
            $('#members').append(listContainer);
        }
        if($('#noUserInfo').length > 0){
            $('#members').empty();
        }
        for(var i in members){
            var member = members[i];
            var master = '', tick = '';
            if(member.id === factionOwner){
                master = ' <span class="label label-danger">圈主</span>';
            }
            if(userId === factionOwner && member.id !== factionOwner){
                tick = '<span class="icon-cross font_size_18 tick_out" data-id="'+member.id+'" data-name="'+member.name+'"></span>';
            }
            html += '<li data-id="'+member.id+'">\
                        <div style="float:left"><img src="/img/'+member.id+'" class="img-rounded size_36"></div>\
                        <div style="float: left; padding-left: 10px;">\
                            <div><a href="/user/'+member.id+'/'+factionId+'">'+member.name+'</a>'+master+'</div>\
                            <div><span class="font_size_12" style="color: #999;">'+(member.position||"")+' '+(member.company||"")+'</span></div>'+tick+'</div>\
                        <div class="clearfix"></div><hr>\
                    </li>';
        }
        $('#memberlist').append(html);
    }else{
        if($('#memberlist').length == 0){
            html = '<div class="jumbotron" style="margin-top: 15px;" id="noUserInfo">\
                            <h1>人气很重要</h1>\
                            <p>邀请志同道合的伙伴加入进来吧</p>\
                            <p>...</p>\
                            <p style="text-align: center">\
                                    <a class="btn btn-success btn-lg" role="button" href="/faction/info/'+factionId+'/'+userId+'">邀请加入</a>\
                            </p>\
                        </div>';
            $('#members').empty();
            $('#members').append(html);
        }else{
            $('#pageNo').val(2);
            $('#loadMore').html('没有更多啦~');
        }
    }
}
function _fetchActs(){
    var pageNo = $('#actPageNo').val();
    $.getJSON('/faction/acts/'+factionId+'/'+pageNo, function(res){
        if(res.error){
            return AlertBox.showTip('加载出错...');
        }
        _renderActsList(res.acts, res.pageNo, res.pageSize);
    })
}
function _renderActsList(acts, pNo, pSize){
    var html = '',len = acts.length;
    if(len > 0){
        for(var i= 0; i<len ;i++){
            var act = acts[i];
            var date = new Date(act.startTime);
            var dateZh = date.format('yyyy年MM月dd号')+'(周'+date.getZhDay(date)+')'
            html += '<div class="bg_white_panel faction_act" style="display: none;">\
                            <div>\
                                <strong><a href="/invite/'+act._id+'">'+act.name+'</a></strong>\
                                <span style="float: right;">'+dateZh+'</span>\
                            </div>\
                            <div>\
                            <span style="color: #666666">发起人:</span>\
                            <img class="img-rounded size_20" src="/img/'+act.creator.id+'" />\
                                    <span class="font_size_12" style="color: #006666;">'+act.creator.name+'</span>\
                            </div>\
                        </div>';
            $('#actlist').append(html);
            $('.faction_act').fadeIn();
        }
        if(len < pSize){
            $('#loadMoreAct').html('没有更多啦～')
        }
        $('#actPageNo').val(pNo);
    }else{

    }
}
